package org.lex.ftplist.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import javax.swing.filechooser.FileNameExtensionFilter;

import org.lex.ftplist.ui.FLApplication;
import org.lex.io.utils.FileUtils;

public class Conf {
	private static final FileFilter INDEX_FILE_FILTER = new FileFilter() {
		private FileNameExtensionFilter filter = new FileNameExtensionFilter("index", "index");

		@Override
		public boolean accept(File pathname) {
			return filter.accept(pathname);
		}

	};

	private static final FileFilter CACHE_FILE_FILTER = new FileFilter() {
		private FileNameExtensionFilter filter = new FileNameExtensionFilter("cache", "cache");

		@Override
		public boolean accept(File pathname) {
			return filter.accept(pathname);
		}

	};

	public static File[] getIndexFiles() {
		return getCacheDirectory().listFiles(INDEX_FILE_FILTER);
	}

	public static File[] getCacheFiles() {
		return getCacheDirectory().listFiles(CACHE_FILE_FILTER);
	}

	public static File getCacheDirectory() {
		File cacheHome = new File(getApplicationHome(), Constants.CACHE_DIR);
		FileUtils.createFolder(cacheHome);
		return cacheHome;
	}

	public static File getApplicationHome() {
		File appHome = FLApplication.getInstance().getContext().getLocalStorage().getDirectory();
		FileUtils.createFolder(appHome);
		return appHome;
	}

	public static BufferedReader openFile(File file) throws FileNotFoundException, UnsupportedEncodingException {
		if (false == file.exists() || false == file.isFile() || false == file.canRead()) {
			return null;
		} else {
			FileInputStream fis = new FileInputStream(file);
			InputStreamReader isr = new InputStreamReader(fis, Constants.ENCODING);
			return new BufferedReader(isr);
		}
	}
}
